<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>支付宝沙箱支付测试工具</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .section {
            margin-bottom: 30px;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .section h3 {
            margin-top: 0;
            color: #333;
        }
        input, textarea, button {
            width: 100%;
            padding: 10px;
            margin: 5px 0;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        button {
            background-color: #1890ff;
            color: white;
            border: none;
            cursor: pointer;
            font-size: 16px;
        }
        button:hover {
            background-color: #40a9ff;
        }
        .result {
            background-color: #f6f8fa;
            border: 1px solid #d0d7de;
            border-radius: 6px;
            padding: 16px;
            margin-top: 10px;
            white-space: pre-wrap;
            font-family: monospace;
            max-height: 300px;
            overflow-y: auto;
        }
        .success {
            background-color: #f0f9ff;
            border-color: #b3d4fc;
            color: #0969da;
        }
        .error {
            background-color: #fff5f5;
            border-color: #fd6c6c;
            color: #d73a49;
        }
        .info-box {
            background-color: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 4px;
            padding: 10px;
            margin: 10px 0;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>支付宝沙箱支付测试工具</h1>
        
        <div class="info-box">
            <strong>沙箱买家账号信息：</strong><br>
            账号：jxamoy@sandbox.com<br>
            登录密码：111111<br>
            支付密码：111111
        </div>

        <!-- JWT Token Section -->
        <div class="section">
            <h3>1. 获取JWT Token</h3>
            <input type="text" id="loginUsername" placeholder="用户名" value="test">
            <input type="password" id="loginPassword" placeholder="密码" value="123456789">
            <button onclick="login()">登录获取Token</button>
            <div id="tokenResult" class="result" style="display:none;"></div>
            <input type="text" id="jwtToken" placeholder="JWT Token (自动填充)" style="margin-top: 10px;">
        </div>        <!-- Create Order Section -->
        <div class="section">
            <h3>2. 创建测试订单 (立即购买模式)</h3>
            <input type="text" id="orderRemark" placeholder="订单备注" value="测试支付宝支付订单">
            <button onclick="createOrder()">创建立即购买订单</button>
            <div id="createOrderResult" class="result" style="display:none;"></div>
            <input type="text" id="orderNo" placeholder="订单号 (自动填充或手动输入)" style="margin-top: 10px;">
        </div>

        <!-- Payment Section -->
        <div class="section">
            <h3>3. 发起支付宝支付</h3>
            <button onclick="payOrder()">发起支付宝支付</button>
            <div id="payResult" class="result" style="display:none;"></div>
            <div id="payUrl" style="margin-top: 10px;"></div>
        </div>

        <!-- Query Order Section -->
        <div class="section">
            <h3>4. 查询订单状态</h3>
            <button onclick="queryOrder()">查询订单详情</button>
            <div id="queryResult" class="result" style="display:none;"></div>
        </div>

        <!-- Test Alipay Direct -->
        <div class="section">
            <h3>5. 直接测试支付宝接口</h3>
            <input type="text" id="testOrderNo" placeholder="测试订单号" value="TEST20250525001">
            <input type="text" id="testAmount" placeholder="金额" value="0.01">
            <input type="text" id="testSubject" placeholder="商品标题" value="测试商品">
            <button onclick="testAlipayDirect()">直接调用支付宝接口</button>
            <div id="alipayDirectResult" class="result" style="display:none;"></div>
        </div>
    </div>

    <script>        const BASE_URL = 'http://localhost:8080';
        let currentToken = '';        // UTF-8 安全的Base64编码
        function utf8ToBase64(str) {
            return btoa(unescape(encodeURIComponent(str)));
        }

        // UTF-8 安全的Base64解码
        function base64ToUtf8(str) {
            return decodeURIComponent(escape(atob(str)));
        }

        // 打开支付宝支付表单
        function openAlipayForm(encodedForm) {
            try {
                // 解码UTF-8安全的Base64编码的表单HTML
                const formHtml = base64ToUtf8(encodedForm);
                
                // 创建新窗口并写入支付表单
                const payWindow = window.open('', '_blank', 'width=800,height=600,scrollbars=yes,resizable=yes');
                if (payWindow) {
                    payWindow.document.write(`
                        <!DOCTYPE html>
                        <html>
                        <head>
                            <title>支付宝支付</title>
                            <meta charset="UTF-8">
                        </head>
                        <body>
                            <div style="text-align: center; padding: 20px;">
                                <h3>正在跳转到支付宝支付页面...</h3>
                                <p>如果没有自动跳转，请点击下方按钮</p>
                            </div>
                            ${formHtml}
                        </body>
                        </html>
                    `);
                    payWindow.document.close();
                } else {
                    alert('无法打开支付窗口，请检查浏览器弹窗设置');
                }
            } catch (error) {
                console.error('打开支付表单失败:', error);
                alert('打开支付页面失败: ' + error.message);
            }
        }

        // 登录获取Token
        async function login() {
            const username = document.getElementById('loginUsername').value;
            const password = document.getElementById('loginPassword').value;
            
            try {
                const response = await fetch(`${BASE_URL}/api/auth/login`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        username: username,
                        password: password,
                        loginType: 1
                    })
                });
                
                const result = await response.json();
                const resultDiv = document.getElementById('tokenResult');
                resultDiv.style.display = 'block';
                
                if (response.ok && result.code === 200) {
                    currentToken = result.data.token;
                    document.getElementById('jwtToken').value = currentToken;
                    resultDiv.className = 'result success';
                    resultDiv.textContent = `登录成功！\nToken: ${currentToken}`;
                } else {
                    resultDiv.className = 'result error';
                    resultDiv.textContent = `登录失败: ${JSON.stringify(result, null, 2)}`;
                }
            } catch (error) {
                const resultDiv = document.getElementById('tokenResult');
                resultDiv.style.display = 'block';
                resultDiv.className = 'result error';
                resultDiv.textContent = `请求失败: ${error.message}`;
            }
        }        // 创建订单
        async function createOrder() {
            const token = document.getElementById('jwtToken').value || currentToken;
            if (!token) {
                alert('请先获取JWT Token');
                return;
            }
            
            const remark = document.getElementById('orderRemark').value;
            
            try {
                const response = await fetch(`${BASE_URL}/api/orders/createNow`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify({
                        selectedCartItems: [],
                        remark: remark,
                        buyNow: true  // 设置为立即购买模式
                    })
                });
                const result = await response.json();
                const resultDiv = document.getElementById('createOrderResult');
                resultDiv.style.display = 'block';
                
                if (response.ok && result.code === 200) {
                    document.getElementById('orderNo').value = result.data;
                    resultDiv.className = 'result success';
                    resultDiv.textContent = `订单创建成功！\n订单号: ${result.data}`;
                } else {
                    resultDiv.className = 'result error';
                    resultDiv.textContent = `创建订单失败: ${JSON.stringify(result, null, 2)}`;
                }
            } catch (error) {
                const resultDiv = document.getElementById('createOrderResult');
                resultDiv.style.display = 'block';
                resultDiv.className = 'result error';
                resultDiv.textContent = `请求失败: ${error.message}`;
            }
        }

        // 发起支付
        async function payOrder() {
            const token = document.getElementById('jwtToken').value || currentToken;
            const orderNo = document.getElementById('orderNo').value;
            
            if (!token) {
                alert('请先获取JWT Token');
                return;
            }
            if (!orderNo) {
                alert('请输入订单号');
                return;
            }
            
            try {
                const response = await fetch(`${BASE_URL}/api/orders/pay`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify({
                        orderNo: orderNo,
                        paymentType: 2  // 支付宝支付
                    })
                });
                
                const result = await response.json();
                const resultDiv = document.getElementById('payResult');
                const payUrlDiv = document.getElementById('payUrl');
                resultDiv.style.display = 'block';
                  if (response.ok && result.code === 200) {
                    resultDiv.className = 'result success';
                    resultDiv.textContent = `支付请求成功！\n${JSON.stringify(result, null, 2)}`;
                      if (result.data && result.data.payUrl) {
                        payUrlDiv.innerHTML = `
                            <p><strong>支付链接已生成，点击下方按钮跳转到支付页面：</strong></p>
                            <button onclick="openAlipayForm('${utf8ToBase64(result.data.payUrl)}')" style="background-color: #52c41a;">
                                🔗 打开支付宝支付页面
                            </button>
                            <p style="font-size: 12px; color: #666; margin-top: 10px;">
                                使用沙箱账号: jfjbwb4477@sandbox.com / 111111
                            </p>
                        `;
                    }
                } else {
                    resultDiv.className = 'result error';
                    resultDiv.textContent = `支付请求失败: ${JSON.stringify(result, null, 2)}`;
                    payUrlDiv.innerHTML = '';
                }
            } catch (error) {
                const resultDiv = document.getElementById('payResult');
                resultDiv.style.display = 'block';
                resultDiv.className = 'result error';
                resultDiv.textContent = `请求失败: ${error.message}`;
            }
        }

        // 查询订单
        async function queryOrder() {
            const token = document.getElementById('jwtToken').value || currentToken;
            const orderNo = document.getElementById('orderNo').value;
            
            if (!token) {
                alert('请先获取JWT Token');
                return;
            }
            if (!orderNo) {
                alert('请输入订单号');
                return;
            }
            
            try {
                const response = await fetch(`${BASE_URL}/api/orders/detail?orderNo=${orderNo}`, {
                    method: 'GET',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                const result = await response.json();
                const resultDiv = document.getElementById('queryResult');
                resultDiv.style.display = 'block';
                
                if (response.ok && result.code === 200) {
                    resultDiv.className = 'result success';
                    const order = result.data.order;
                    const statusText = ['待支付', '已支付', '已发货', '已完成', '已取消'][order.status];
                    resultDiv.textContent = `订单查询成功！\n订单号: ${order.orderNo}\n状态: ${statusText} (${order.status})\n金额: ${order.totalAmount}\n支付时间: ${order.paymentTime || '未支付'}\n\n完整信息:\n${JSON.stringify(result.data, null, 2)}`;
                } else {
                    resultDiv.className = 'result error';
                    resultDiv.textContent = `查询订单失败: ${JSON.stringify(result, null, 2)}`;
                }
            } catch (error) {
                const resultDiv = document.getElementById('queryResult');
                resultDiv.style.display = 'block';
                resultDiv.className = 'result error';
                resultDiv.textContent = `请求失败: ${error.message}`;
            }
        }

        // 直接测试支付宝接口
        async function testAlipayDirect() {
            const token = document.getElementById('jwtToken').value || currentToken;
            const orderNo = document.getElementById('testOrderNo').value;
            const amount = document.getElementById('testAmount').value;
            const subject = document.getElementById('testSubject').value;
            
            if (!token) {
                alert('请先获取JWT Token');
                return;
            }
            
            try {
                const response = await fetch(`${BASE_URL}/api/alipay/pay`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify({
                        orderNo: orderNo,
                        totalAmount: amount,
                        subject: subject,
                        body: '支付宝沙箱测试订单'
                    })
                });
                
                const result = await response.json();
                const resultDiv = document.getElementById('alipayDirectResult');
                resultDiv.style.display = 'block';
                  if (response.ok && result.code === 200) {
                    resultDiv.className = 'result success';
                    resultDiv.textContent = `支付宝接口调用成功！\n${JSON.stringify(result, null, 2)}`;
                      if (result.data && result.data.payUrl) {
                        resultDiv.innerHTML += `
                            <div style="margin-top: 10px;">
                                <button onclick="openAlipayForm('${utf8ToBase64(result.data.payUrl)}')" style="background-color: #52c41a; width: auto; padding: 8px 16px;">
                                    🔗 打开支付宝支付页面
                                </button>
                            </div>
                        `;
                    }
                } else {
                    resultDiv.className = 'result error';
                    resultDiv.textContent = `支付宝接口调用失败: ${JSON.stringify(result, null, 2)}`;
                }
            } catch (error) {
                const resultDiv = document.getElementById('alipayDirectResult');
                resultDiv.style.display = 'block';
                resultDiv.className = 'result error';
                resultDiv.textContent = `请求失败: ${error.message}`;
            }
        }
    </script>
</body>
</html>
